package com.bancomer.batch.validators.impl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.bancomer.batch.Constants;
import com.bancomer.batch.MapConstants;
import com.bancomer.batch.pojo.Alert;
import com.bancomer.batch.pojo.FileHelper;
import com.bancomer.batch.pojo.ValidationResult;
import com.bancomer.batch.util.FilesWriter;
import com.bancomer.batch.util.NumberComparator;
import com.bancomer.batch.validators.GeneralValidator;

public class ConceptAlertValidator implements GeneralValidator{
	private StringBuffer condition = new StringBuffer();
	@Override
	public ValidationResult executeValidation(FileHelper fileHelper,
			Object... obj) {
		ValidationResult result = new ValidationResult();
		try {
			result = validateConcepts(fileHelper,(Alert)obj[0]);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setMessage(e.getMessage());
			result.setSucces(false);
		}
		return result;
	}
	
	public ValidationResult validateConcepts(FileHelper fileHelper, Alert alert){
		ValidationResult result = new ValidationResult();
		Map<String,String> conceptFilter = new HashMap<String,String>();
		FileHelper parameterFile = null;
		FileReader input = null;
		BufferedReader buffer = null;
		String positions;
		String names;
		String[] columnsPositions;
		String[] columnsNames;
		String line;
		String load="";
		Map<String,int[]> columnPositions = new HashMap<String, int[]>();
		
		for(FileHelper file : alert.getOutputFiles()){
			if(file.getName().equals("pigScriptParameters.properties")){
				parameterFile = file;
				break;
			}
		}
		try{
			MapConstants properties = MapConstants.getInstance(alert.getProperties().getProperty("constantsFile"));
			final Properties alertConstants = properties.getConstants();
			input = new FileReader(parameterFile.getLocalPath()+parameterFile.getName());
			buffer = new BufferedReader(input);
			line=buffer.readLine();
			while(line!=null){
				if(line.contains(fileHelper.getProperties().getProperty("layoutName"))){
					load = line.split("=")[1];
					break;
				}
				line = buffer.readLine();
			}
			buffer.close();
			load = load.replace("com.bancomer.pig.functions.IndexOfLoader", "");
			load = load.replaceAll("[\\(\\'\\ \\)]","");
			positions = load.split("as")[0];
			names = load.split("as")[1];
			columnsPositions = positions.split(",");
			columnsNames = names.split(",");
	
			for(int i=0;i<columnsPositions.length;i++){
				int[] indexPositions = new int[2];
				indexPositions[0]=Integer.valueOf(columnsPositions[i].split("-")[0]);
				indexPositions[1]=Integer.valueOf(columnsPositions[i].split("-")[1]);
				columnPositions.put(columnsNames[i].split(":")[0],indexPositions);
			}
		
			input = new FileReader(fileHelper.getLocalPath()+fileHelper.getName());
			buffer = new BufferedReader(input);	
			line = buffer.readLine();
			while (line != null)   {
				int[] indexPositions;
				indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CONCEPT_COL1"));
				String alertIndicator = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
				indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CONCEPT_COL2"));
				String alert06 = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
				indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CONCEPT_COL3"));
				String concept = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim(); 
				if((!"".equals(alertIndicator)&&alertConstants.getProperty("ALE").equals(alertIndicator))&&(!"".equals(alert06)&&alertConstants.getProperty("ALERT_06").equals(alert06))){
					condition.append("TRIM($3) == '"+concept+"' OR "); 
				}
				line = buffer.readLine();
	    	}
			if("".equals(condition.toString().trim())){
				result.setMessage("No existen conceptos para la alerta "+alert.getName()+" en el archivo "+fileHelper.getName());
				result.setSucces(false);
				buffer.close();
				return result;
			}
			condition.delete(condition.length()-4,condition.length());
			buffer.close();
			conceptFilter.put("conceptFilter", condition.toString());
			FilesWriter.writePropertiesFile(parameterFile,conceptFilter);
		}
		catch(Exception e){
			result.setMessage("Class: ConceptAlertValidator - "+e.getMessage());
			result.setSucces(false);
		}
		
		return result;
		
	}
}
